<template>
  <d2-container>
  <div class="app-container">
    <el-container :style="'height:'+containerHeight+'px'">
      <el-main class="theme-front-color">
        <el-row>
          <div class="search-area">
            <el-form label-position="right" :model="dataForm" :inline="true">
              <div style="font-size:15px;display:inline-block; float:left;">
                <!--<el-form-item label="分类" label-width="40px">-->
                  <!--<el-select v-model="dataForm.energyType"  style="width: 100px;" placeholder="请选择"  size="mini" @change="changeMeter">-->
                    <!--<el-option-->
                      <!--v-for="(item, index) in meterTypeList" :key="index"-->
                      <!--:label="item.paramValue"-->
                      <!--:value="item.paramKey">-->
                    <!--</el-option>-->
                  <!--</el-select>-->
                <!--</el-form-item>-->
                <el-form-item label="采集分类" prop="collectType">
                  <el-select v-model="dataForm.collectType" style="width:100%;"  @change="changeMeter">
                    <el-option v-for="item in meterTypeParamValueList" :key="item.collectType" :label="item.collectName" :value="item.collectType">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="日期" label-width="40px">
                    <el-date-picker
                      v-model="dataForm.date"
                      placeholder="时间范围"
                      style="width: 250px;"
                      class="filter-item"
                      size="mini"
                      :format="dataForm.dateFormat"
                      :type="dataForm.dateTypeStr"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      suffix-icon="el-icon-date"
                      clearable
                      @keyup.enter.native="getPowerDataList"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-radio-group v-model="dataForm.dateType" size="mini" @change="changeDateType">
                      <el-radio-button :label="item.typeDesc" v-for="(item, index) in searchDate" :key="index" >
                        {{item.label}}
                      </el-radio-button>
                    </el-radio-group>
                </el-form-item>
              </div>
              <div style="display:inline-block; float:right;">
                <el-form-item>
                  <el-button
                    class="filter-item"
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="getPowerDataList"
                  >查询</el-button>
                  <!-- <el-button
                      class="filter-item"
                      type="primary"
                      icon="el-icon-download"
                      size="mini"
                      @click="exoprtData"
                  >导出</el-button> -->
                </el-form-item>
              </div>
            </el-form>
          </div>
        </el-row>
        <div style="margin-top:20px;">
          <el-row :gutter="10">
            <el-col :span="24">
              <div id="businessAreaChart" class="busi-chart" :style="'height:'+chartHeight+'px;'"></div>
            </el-col>
          </el-row>
        </div>
      </el-main>
      <el-aside class="tree-area">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="设备" name="1">
            <el-table ref="deviceTable" :show-header="false" highlight-current-row current-row-key="objId" empty-text="无设备信息" @row-click="selectRent" :data="dataList" :height="containerHeight-20" style="width: 99%;">
              <el-table-column min-width="100"  prop="objName" header-align="left" align="left"></el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="区域" name="2">
            <el-table ref="buildTable" :show-header="false" highlight-current-row current-row-key="objId" empty-text="无区域信息" @row-click="selectRent" :data="dataList" :height="containerHeight-20" style="width: 99%;">
              <el-table-column min-width="100"  prop="objName" header-align="left" align="left"></el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="部门" name="3">
            <el-table ref="areaTable" :show-header="false" highlight-current-row current-row-key="objId" empty-text="无区域信息" @row-click="selectRent" :data="dataList" :height="containerHeight-20" style="width: 99%;">
              <el-table-column min-width="100"  prop="objName" header-align="left" align="left"></el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>

      </el-aside>
    </el-container>
  </div>
  </d2-container>
</template>

<script>
import * as Util from "@/utils";
import * as Echarts from 'echarts'
export default {
  name: "increase",
  data() {
    return {
      activeName:'1',
      searchDate: [
        {
            label: '日',
            date: 'date',
            typeDesc: '3',
            format: 'YYYY-mm-dd 00:00:000',
            chartShowFormat:'YYYY-mm-dd:',
            formatStr: 'yyyy-MM-dd',
            disabled:false
        }, {
            label: '月',
            date: 'month',
            typeDesc: '4',
            format: 'YYYY-mm-01 00:00:00',
            chartShowFormat:'YYYY-mm-',
            formatStr: 'yyyy-MM',
            disabled:false
        }, {
            label: '年',
            date: 'year',
            typeDesc: '5',
            format: 'YYYY-01-01 00:00:00',
            chartShowFormat:'YYYY-',
            formatStr: 'yyyy',
            disabled:false
      }],
      dataForm: {
        collectType:'',
        date:new Date(),
        dateType:'3',
        energyType:this.$meterType.ELECTRIC,
        dateFormat:'yyyy-MM-dd',
        dateTypeStr:'date',
      },
      page: {
        page: 1,
        total: 0,
        size: 10
      },
      buildTreeProps: {
        label: "buildingName",
        children: "children"
      },
      orgTreeProps: {
        label: "organizationName",
        children: "children"
      },
      unit:'',
      dataList:[],
      dataDeviceList: [],
      dataBuildingList: [],
      dataOrgList:[],
      meterTypeList:[],
      currentSelectInfo: {},
      departTableDataList:[],
      meterTypeParamValueList:[],
      businessChart:{
          chart:"",
          x:[],
          y:[],
          data:[],
          warn:0,
          title:"用能情况"
      },
      color:['#708DE5','#2BD597', '#F6AD35'],
      sourceData:'',
    };
  },
  computed: {
    containerHeight() {
      return Util.getClientHeight() - 143;
    },
    chartHeight(){
       return Util.getClientHeight() - 300;
    }
  },
  created() {
    this.dataForm.dateFormat = this.searchDate[0].formatStr;
    this.querySubitem('')
   // this.queryStatic("meterType");
    // this.getDeviceList();
    // this.getDepartList();
    // this.getBuildInfoList();
  },
  methods: {
    querySubitem(meterType){
      //查询子分类
      this.queryCollectType(meterType,'1',data=>{
        if (data && data.code === 0) {
        this.meterTypeParamValueList = data.page.list;
        if( data.page.list&& data.page.list.length>0){
          this.dataForm.collectType = data.page.list[0].collectType
          this.unit = data.page.list[0].collectUnit;
        }
        this.getDeviceList();
        this.getDepartList();
        this.getBuildInfoList();
      } else {
        this.meterTypeParamValueList = [];
      }
    });
    },
    /**
     * 获取采集分项
     */
    queryCollectType(type,paramValue,callback) {
      let params = {
        'meterType': type ,
        'state': '1' ,
        'cumulativeType':paramValue,
        "customerId":this.$util.cookies.get('customer_id'),
        'page': 1,
        'limit': 10000,
      }
      this.$api.okhttp({
        url: this.$http.adornUrl('/ecs/ecscollectitem/list'),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then((data) => {
        if(callback){
          callback(data);
        }
      });
    },
    changeMeter(){
      this.activeName = '1';
     // this.querySubitem(this.dataForm.energyType)
      this.getDeviceList();
      this.getDepartList();
      this.getBuildInfoList();
    },
    changeDateType(val){
      this.dataForm.date = new Date();
      this.searchDate.forEach(ele=>{
        if(ele.typeDesc==val){
          this.dataForm.dateFormat = ele.formatStr;
          //ele.disabled = false;
        }
        else{
          //ele.disabled = true;
        }
      })
      this.activeName = '1';
      this.getDeviceList();
      this.getDepartList();
      this.getBuildInfoList();
    },
    handleClick(){
      if(this.activeName=='1'){
        this.dataList = this.dataDeviceList;
      }else if(this.activeName=='2'){
        this.dataList = this.dataBuildingList;
      }
      else if(this.activeName=='3'){
        this.dataList = this.dataOrgList;
      }
    },
    // 获取设备数据列表
    getDeviceList () {
      this.$api.okhttp({
        url: this.$http.adornUrl("/ecs/ecsquotainfo/increaseRecordList/1"),
        method: 'get',
        params: this.$http.adornParams({
          'page': 1,
          'limit': 10000,
          'dateType':this.dataForm.dateType,
          'meterType':this.dataForm.energyType , //能耗分类
          'collectType':this.dataForm.collectType,
          'key': '',
          'projectId': this.$util.cookies.get("cuuren_projectId"),
          "customerId":this.$util.cookies.get('customer_id')
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.dataDeviceList =data.list;
          this.dataList = this.dataDeviceList;
          if(this.dataDeviceList.length>0){
            this.$refs.deviceTable.setCurrentRow(this.dataDeviceList[0]);
            this.selectRent(this.dataDeviceList[0]);
          }
        } else {
          this.dataDeviceList = []
        }
      })
    },
    selectRent(row){
      this.currentSelectInfo = row;
      this.dataForm.dateType = row.quotaUnit;
     // this.changeDateType(row.quotaUnit);
      this.getPowerDataList();
    },
     // 获取区域树
    getBuildInfoList() {
      this.$api.okhttp({
        url: this.$http.adornUrl("/ecs/ecsquotainfo/increaseRecordList/2"),
        method: "get",
        params: this.$http.adornParams({
          'page': 1,
          'limit': 10000,
          'dateType':this.dataForm.dateType,
          'meterType':this.dataForm.energyType , //能耗分类
          'collectType':this.dataForm.collectType,
          'key': '',
          "customerId":this.$util.cookies.get('customer_id'),
          'projectId': this.$util.cookies.get("cuuren_projectId"),
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.dataBuildingList = data.list;
        } else {
          this.dataBuildingList = [];
        }
      });
    },
    // 获取部门数据列表
    getDepartList () {
      this.$api.okhttp({
        url: this.$http.adornUrl("/ecs/ecsquotainfo/increaseRecordList/3"),
        method: 'get',
        params: this.$http.adornParams({
          'page': 1,
          'limit': 10000,
          'dateType':this.dataForm.dateType,
          'meterType':this.dataForm.energyType , //能耗分类
          'collectType':this.dataForm.collectType,
          'key': '',
          "customerId":this.$util.cookies.get('customer_id'),
          'projectId': this.$util.cookies.get("cuuren_projectId")
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.dataOrgList =data.list;
        } else {
          this.dataOrgList = []
        }
      })
    },
    /**
     * 获取参数枚举
     */
    queryStatic(type) {
      this.$api.okhttp({
        url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
        method: 'get',
        params: this.$http.adornParams({
          'code': type ,
          "customerId":this.$util.cookies.get('customer_id')
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.meterTypeList = data.page
          this.dataForm.energyType = data.page[0].paramKey;
          this.unit = data.page[0].paramExt;
          this.querySubitem(this.dataForm.energyType)
        } else {
          this.meterTypeList = []
        }
       // this.getDataList();
      });
    },
    getPowerDataList() {
      //console.log(Util.dateFormat(this.searchDate.filter(ele=>ele.typeDesc==this.currentSelectInfo.quotaUnit)[0].format,this.dataForm.date));
      let params = {
          customerId: this.$util.cookies.get("customer_id"),
          meterType:this.dataForm.energyType , //能耗分类
          collectType:this.dataForm.collectType,
          objType: this.activeName,    //对象类型 1:设备 2:区域 3:部门
          objId:this.currentSelectInfo.objId,    //对象id
          dateType :this.currentSelectInfo.quotaUnit,//2:按小时 3:按天, 4:按月 5:年
          date:Util.dateFormat(this.searchDate.filter(ele=>ele.typeDesc==this.currentSelectInfo.quotaUnit)[0].format,this.dataForm.date), //日期
          quotaId:this.currentSelectInfo.quotaId //指标Id
      }
      this.$api.okhttp({
        url: this.$http.adornUrl('/ecm/alarmInc/list'),
        method: 'post',
        data: this.$http.adornData(params)
      }).then((data) => {
        if (data && data.code === 0) {
          //console.log('所有数据',data.data)
          this.sourceData =data.data;
          this.handleDataList(data.data)

        }
      });
    },
    handleDataList(data){
      //处理返回的所有的数据
      this.businessChart={
          chart:"",
          x:[],
          data:[],
          title:""
      };
      let selectType=this.meterTypeParamValueList.find(item=>item.collectType==this.dataForm.collectType).collectName
      this.businessChart.title=`${selectType}增幅预警`;
      if(this.dataForm.dateType==='4') {
        let date = new Date(new Date(this.dataForm.date).getFullYear(), new Date(this.dataForm.date).getMonth() + 1, 0).getDate()
        data.quotaTime =  data.quotaTime.slice(0,date)
      }
      data.quotaTime.forEach((item,index)=>{
        //图表一
        this.businessChart.x.push(item.timePoint);
        this.businessChart.data.push(0);
        data.list.forEach(ele=>{
          if(ele.dateDetail==item.timePoint){
            this.businessChart.data[index]=ele.val;
          }
        })

        //表格数据
      })

      this.initBarChartOne(this.businessChart,'businessAreaChart');
    },
    initBarChartOne(opt,obj){
      let vm = this;
      let option={
          grid:{
            x:50,
            y:30,
            x2:55,
            y2:25,
          },
          title:{
              text:opt.title,
              show:true,
              left:'center',
              top:5,
              textStyle:{
                  color:"#ccc",
                  fontSize:14,
                  fontFamily:"MicrosoftYaHei",
                  lineHeight:14,
              },
              padding:0,
          },
          tooltip: {
            trigger: 'item',
            formatter: function (params, ticket, callback){
              let quoTime = vm.sourceData.quotaTime[params.dataIndex].val;
              let date = Util.dateFormat(vm.searchDate.find(ele=>ele.typeDesc==vm.dataForm.dateType).chartShowFormat,new Date(vm.dataForm.date));
              return date+params.name+"<br/>增幅值："+params.value+"（"+vm.unit+"）<br/>预警值："+quoTime+"（"+vm.unit+"）";
            }
          },
          legend:{
            right:80,
            top:-5,
            data:[{name:'指标值'}]
          },
          xAxis:{
              type:'category',
              data:opt.x,

              axisLine:{
                  lineStyle:{
                      color:"#2C73D2",
                      type:'solid',
                      width:0.5
                  },
              },
              axisLabel:{
                  color:"#ccc",
                  interval:0,
              },
              axisTick: {
                show:false,
                alignWithLabel: true
              }
          },
          yAxis:{
              type:'value',
              name:'单位:'+this.unit,
              data:opt.y,
              splitNumber :10,
              minInterval:5,
              // max: function(){
              //   return max+20;
              // },
              axisLabel:{
                  color:"#ccc",
              },
              axisLine:{
                  lineStyle:{
                      color:"#ccc",
                      type:'soild',
                      opacity:0,
                  }
              },
              axisLabel:{
                  formatter:function(value,index){
                    if(value>1000000){
                      return value/(1000000)+"M";
                    }
                    else if(value>1000){
                      return value/1000+"k";
                    }
                    return value;
                  }
              },
              axisTick: {
                  show:false,
                  alignWithLabel: true
              },
              splitLine:{
                  lineStyle:{
                      color:"#2C73D2",
                      type:"dotted",
                      opacity:0.5,
                  }
              },
          },
          series: [{
              name: '用量',
              type: 'bar',
              data: opt.data,
              barCategoryGap:'40%',
              itemStyle:{
                normal: {
                  color:function(params){
                    let ele = vm.sourceData.quotaTime[params.dataIndex];
                    if(params.value>0){
                      if(params.value<=ele.val){
                        return 'rgb(76,126,223)';
                      }
                      else{
                        return '#FF0000';
                      }
                    }
                    else{
                        return 'rgb(76,126,223)';
                    }
                    return 'rgb(76,126,223)';
                  },
                  barBorderRadius:[14,14,0,0],
                },
              },
            //   markLine : {
            //     symbol:"none",               //去掉警戒线最后面的箭头
            //     label:{
            //         position:"end",         //将警示值放在哪个位置，三个值“start”,"middle","end"  开始  中点 结束
            //     },
            //     lineStyle:{
            //       normal:{
            //         color:"rgb(245,108,108)",
            //         type:"solid",
            //       }
            //     },
            //     data : [{
            //         silent:false,             //鼠标悬停事件  true没有，false有
            //         lineStyle:{               //警戒线的样式  ，虚实  颜色
            //             type:"solid",
            //             color:"rgb(245,108,108)"
            //         },
            //         name: '增幅界限',
            //         yAxis: opt.warn
            //     }]
            // }
          }],
      }
      //console.log(JSON.stringify(option));
      opt.chart = Echarts.init(document.getElementById(obj));
      opt.chart.setOption(option);
    },
  },
  watch:{
    'dataForm.collectType':function(newV,oldV){
      this.unit = this.meterTypeParamValueList.find(item=>item.collectType==this.dataForm.collectType).collectUnit;
    },
    'dataForm.dateType':function(newV,oldV){
      this.dataForm.dateTypeStr = this.searchDate.find(item=>item.typeDesc==this.dataForm.dateType).date
    }
  }
};
</script>

<style scoped>
.tree-area { background-color: rgba(0, 0, 0, 0.1);
  width: 250px !important;
  /* box-shadow: 0px 0px 2px 2px #f7f6f6; */
  /* border: solid 1px #808080; */
  padding-top: 10px;
  padding-left: 15px;
}
.bg-white {
  box-shadow: 0px 0px 2px 2px #f7f6f6;
}
.el-tree-node__content {
  height: 30px !important;
}
.busi-chart{
    width: 100%;
    height: 250px;
    margin-top: 10x;
    margin-bottom: 20px;
}
.el-form-item{
  margin-bottom: 0px;
}
.search-area{
   display:flow-root;
   margin-bottom: 10px;
   border: 1px solid #808080;
   border-left: none;
   border-right: none;
   padding: 10px 0px 10px 0px;
}
</style>
